var express = require('express');
var router = express.Router();
const app = express();

var { FoodModel, OrderModel, MemberModel, registerModel } = require("../model/db.js");

const cors = require("cors");
const { body, validationResult } = require('express-validator');

const tencentcloud = require('tencentcloud-sdk-nodejs-iai');


const bcrypt = require('bcrypt');
const saltRounds = 12; // 成本因子

let AlipaySdk = require("alipay-sdk")
let AlipaySdkFormData = require("alipay-sdk/lib/form")

// 使用中间件
app.use(cors());
app.use(express.json());

// 状态映射
const STATUS_MAP = {
    unpaid: '待付款',
    unsent: '待发货',
    unreceived: '待收货',
    uncommented: '待评论',
    completed: '已完成'
};


// 李键良

router.post('/api/trueFace', async (req, res) => {
    try {
      const body = req.body;
      const base64 = body.base64;
      const needBlink = body.NeedBlinkDetection;
      const detectHeadPose = body.detectHeadPose;
      const needMouthOpen = body.NeedMouthOpenDetection;
  
      const IaiClient = tencentcloud.iai.v20200303.Client;
      const clientConfig = {
        credential: {
          //密钥和id值  https://console.cloud.tencent.com/cam/capi获取秘钥和id值
          secretId: 'AKIDd7PVO5g8NPEtMdkePxHOHzUloeFdnkT0',
          secretKey: 'VdaKsENI0VmphMq7B1dNyMXWHqCKFxRh',
        },
        region: 'ap-beijing', //人脸识别库的地区  华北地区-北京
        profile: {
          httpProfile: {
            endpoint: 'iai.tencentcloudapi.com',
          },
        },
      };
      // 实例化要请求产品的client对象,clientProfile是可选的
      const client = new IaiClient(clientConfig);
  
      if (detectHeadPose) {
        // 检测头部姿态
        const params = {
          Image: base64,
          NeedFaceAttributes: 1,
        };
  
        const result = await client.DetectFace(params);
        
        if (!result?.FaceInfos?.[0]) {
          return res.json({
            code: -1,
            msg: "未检测到人脸或接口返回异常",
          });
        }
  
        const faceInfo = result.FaceInfos[0];
        const faceAttr = faceInfo.FaceAttributesInfo;
        const headPose = faceAttr && faceAttr.Pitch !== undefined ? {
          Pitch: faceAttr.Pitch,
          Yaw: faceAttr.Yaw,
          Roll: faceAttr.Roll
        } : null;
  
        if (!headPose) {
          return res.json({ 
            code: -1, 
            msg: '未检测到头部姿态' 
          });
        }
  
        // 判断头部姿态
        let headPoseStatus = '正面';
        if (headPose.Pitch > 20) {
          headPoseStatus = '仰头';
        } else if (headPose.Pitch < -20) {
          headPoseStatus = '低头';
        } else if (typeof headPose.Yaw === 'number' && headPose.Yaw > 20) {
          headPoseStatus = '左转';
        } else if (typeof headPose.Yaw === 'number' && headPose.Yaw < -20) {
          headPoseStatus = '右转';
        }
  
        return res.json({
          code: 0,
          headPose: headPoseStatus,
          msg: "检测成功",
        });
      } else if (needMouthOpen) {
        // 张嘴检测
        const params = {
          Image: base64,
          NeedFaceAttributes: 1
        };
  
        const result = await client.DetectFace(params);
        
        if (!result?.FaceInfos?.[0]) {
          return res.json({
            code: -1,
            msg: "未检测到人脸或接口返回异常"
          });
        }
  
        const faceInfo = result.FaceInfos[0];
        const faceAttr = faceInfo.FaceAttributesInfo;
        
        // 需要检查嘴部状态
        // 检查是否有表情相关属性
        if (!faceAttr || !faceAttr.Expression) {
          return res.json({
            code: -2,
            msg: "未检测到表情相关属性"
          });
        }
        
        // 获取表情的值，直接使用表情值来判断嘴部状态
        // Expression值范围是[0-100]，值越大表示表情越明显
        const expressionValue = faceAttr.Expression;
        
        // 判断是否张嘴，可以根据表情值来判断
        // 表情值大于60时，认为用户张嘴表情明显
        if (expressionValue > 15) {
          // 张嘴成功
          return res.json({
            code: 0,
            mouthOpen: true,
            expressionValue: expressionValue,
            msg: "张嘴检测成功"
          });
        } else {
          return res.json({
            code: 1,
            mouthOpen: false,
            expressionValue: expressionValue,
            msg: "请张大嘴巴"
          });
        }
      } else if (needBlink) {
        // 眨眼检测
        const params = {
          Image: base64,
          NeedFaceAttributes: 1
        };
  
        const result = await client.DetectFace(params);
        
        if (!result?.FaceInfos?.[0]) {
          return res.json({ 
            code: -1, 
            msg: "未检测到人脸或接口返回异常" 
          });
        }
  
        const faceInfo = result.FaceInfos[0];
        const faceAttr = faceInfo.FaceAttributesInfo;
        const eyeOpen = faceAttr && typeof faceAttr.EyeOpen !== 'undefined' ? faceAttr.EyeOpen : null;
  
        if (eyeOpen === false) {
          // 眨眼成功，进行人脸识别
          const searchParams = {
            GroupIds: ["10011"],
            Image: base64,
            NeedPersonInfo: 1,
            QualityControl: 0,
            FaceMatchThreshold: 85,
          };
  
          const searchResult = await client.SearchFaces(searchParams);
  
          if (!searchResult?.Results?.[0]?.Candidates?.length) {
            return res.json({
              code: 2,
              blink: true,
              msg: "眨眼成功，但该人员没有注册"
            });
          }
  
          const { FaceId, Gender, PersonId, PersonName } = searchResult.Results[0].Candidates[0];
          return res.json({
            code: 0,
            blink: true,
            data: { FaceId, Gender, PersonId, PersonName },
            msg: "眨眼并识别成功"
          });
        } else if (eyeOpen === true) {
          return res.json({ 
            code: 1, 
            blink: false, 
            msg: "请眨眼" 
          });
        } else {
          return res.json({ 
            code: -2, 
            msg: "未检测到眼睛状态" 
          });
        }
      } else {
        // 正常人脸识别流程
        const params = {
          GroupIds: ["10011"],
          Image: base64,
          NeedPersonInfo: 1,
          QualityControl: 0,
          FaceMatchThreshold: 85,
        };
  
        const searchResult = await client.SearchFaces(params);
  
        if (!searchResult?.Results?.[0]?.Candidates?.length) {
          return res.json({
            code: -1,
            msg: "该人员没有注册",
          });
        }
  
        const { FaceId, Gender, PersonId, PersonName } = searchResult.Results[0].Candidates[0];
        return res.json({
          code: 0,
          data: {
            FaceId,
            Gender,
            PersonId,
            PersonName,
          },
          msg: "识别成功",
        });
      }
    } catch (error) {
      console.error('人脸识别API错误:', error);
      return res.json({
        code: 500,
        msg: '服务器内部错误',
      });
    }
  });

router.post('/login', async (req, res) => {
    try {
        const { username, password } = req.body;
        
        // 根据用户名查找用户
        const user = await registerModel.findOne({ username: username });
        if (!user) {
            return res.send({ code: 400, message: '用户名或密码不正确' });
        }
        
        // 使用bcrypt比较密码哈希值
        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) {
            return res.send({ code: 400, message: '用户名或密码不正确' });
        }
        
        // 登录成功
        res.send({ code: 200, message: '登录成功', userId: user._id });
    } catch (error) {
        console.error('登录失败:', error);
        res.send({ code: 500, message: '服务器错误，登录失败' });
    }
});

router.post('/register', async (req, res) => {
    try {
        const { username, password } = req.body;

        // 检查用户名是否已存在
        const existingUser = await registerModel.findOne({ username });
        if (existingUser) {
            return res.send({
                code: 400,
                message: '用户名已存在，请选择其他用户名'
            });
        }

        // 对前端哈希值进行二次哈希
        const salt = await bcrypt.genSalt(saltRounds);
        const dbHash = await bcrypt.hash(password, salt);

        // 存储到数据库
        await registerModel.create({ username: username, password: dbHash });

        res.send({
            code: 200,
            message: '注册成功'
        });
    } catch (error) {
        console.error('注册失败:', error);
        res.send({
            code: 500,
            message: '服务器错误，注册失败'
        });
    }
});

// 获取食品列表
router.get('/food', async function (req, res, next) {
    try {
        const data = await FoodModel.find({}).lean();
        res.json({ code: 200, data });
    } catch (err) {
        console.error('获取食品列表失败:', err);
        res.status(500).json({ code: 500, message: '获取食品列表失败' });
    }
});

// 获取订单列表
router.get('/orders', async function (req, res, next) {
    try {
        const { status, userId } = req.query;

        if (!userId) {
            return res.status(400).json({ code: 400, message: '用户ID不能为空' });
        }

        let query = { userId };
        if (status && STATUS_MAP[status]) {
            query.status = status;
        }

        const orders = await OrderModel.find(query)
            .sort({ createdAt: -1 })
            .lean();

        const formattedOrders = orders.map(order => ({
            id: order._id,
            title: order.items.length > 0 ?
                `${order.items[0].title}${order.items.length > 1 ? `等${order.items.length}件商品` : ''}` :
                '订单商品',
            price: order.totalAmount,
            status: STATUS_MAP[order.status] || order.status,
            time: new Date(order.createdAt).toLocaleString()
        }));

        // 如果前端需要按状态分类返回
        if (!status) {
            const result = {
                unpaid: formattedOrders.filter(o => o.status === '待付款'),
                unsent: formattedOrders.filter(o => o.status === '待发货'),
                unreceived: formattedOrders.filter(o => o.status === '待收货'),
                uncommented: formattedOrders.filter(o => o.status === '待评论')
            };
            return res.json({ code: 200, data: result });
        }

        res.json({ code: 200, data: formattedOrders });
    } catch (error) {
        console.error('获取订单失败:', error);
        res.status(500).json({ code: 500, message: '获取订单失败' });
    }
});

// 创建订单
router.post('/orders', [
    body('userId').notEmpty().withMessage('用户ID不能为空'),
    body('items').isArray({ min: 1 }).withMessage('订单商品不能为空'),
    body('totalAmount').isNumeric().withMessage('订单金额必须为数字'),
    body('shippingAddress').notEmpty().withMessage('收货地址不能为空'),
    body('contactPhone').isMobilePhone('zh-CN').withMessage('联系电话格式不正确')
], async function (req, res, next) {
    try {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ code: 400, errors: errors.array() });
        }

        const { userId, items, totalAmount, shippingAddress, contactPhone } = req.body;

        const newOrder = new OrderModel({
            userId,
            items,
            totalAmount,
            shippingAddress,
            contactPhone,
            status: 'unpaid'
        });

        await newOrder.save();

        res.status(201).json({
            code: 201,
            message: '订单创建成功',
            data: {
                id: newOrder._id,
                status: '待付款'
            }
        });
    } catch (error) {
        console.error('创建订单失败:', error);
        res.status(500).json({ code: 500, message: '创建订单失败' });
    }
});

// 更新订单状态
router.put('/orders/:id/status', [
    body('status').isIn(Object.keys(STATUS_MAP)).withMessage('无效的订单状态')
], async function (req, res, next) {
    try {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ code: 400, errors: errors.array() });
        }

        const { id } = req.params;
        const { status } = req.body;

        const updatedOrder = await OrderModel.findByIdAndUpdate(
            id,
            { status, updatedAt: Date.now() },
            { new: true }
        );

        if (!updatedOrder) {
            return res.status(404).json({ code: 404, message: '订单未找到' });
        }

        res.json({
            code: 200,
            message: '订单状态更新成功',
            data: {
                id: updatedOrder._id,
                status: STATUS_MAP[status] || status
            }
        });
    } catch (error) {
        console.error('更新订单状态失败:', error);
        res.status(500).json({ code: 500, message: '更新订单状态失败' });
    }
});

router.post('/member', [
    body('amount').isNumeric().withMessage('金额必须为数字'),
    body('duration').isIn(['month', 'quarter', 'year']).withMessage('无效的时长')
], async function (req, res, next) {
    try {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ code: 400, errors: errors.array() });
        }

        const { amount, duration } = req.body;

        // 计算VIP等级 (根据金额决定)
        let vipLevel = 1;
        if (amount >= 800) vipLevel = 3;
        else if (amount >= 500) vipLevel = 2;

        // 计算到期时间
        const now = new Date();
        let expireDate = new Date();

        if (duration === 'month') {
            expireDate.setMonth(now.getMonth() + 1);
        } else if (duration === 'quarter') {
            expireDate.setMonth(now.getMonth() + 3);
        } else if (duration === 'year') {
            expireDate.setFullYear(now.getFullYear() + 1);
        }

        // 判断会员类型
        const memberType = amount >= 500 ? '黄金会员' : '普通会员';

        // 创建会员记录
        const member = new MemberModel({
            memberType,
            startDate: now,
            expireDate,
            amount,
            vipLevel,
            isAutoRenew: false
        });

        await member.save();

        res.json({
            code: 200,
            message: '会员开通成功',
            data: {
                memberType,
                vipLevel,
                expireDate: expireDate.toISOString(),
                amount
            }
        });
    } catch (error) {
        console.error('开通会员失败:', error);
        res.status(500).json({ code: 500, message: '开通会员失败' });
    }
});

//支付宝
router.post('/alipay', async function (req, res) {
  // 实例化商家信息 把网站付款的钱付给哪个商家
  let { outTradeNo, subject, totalAmount } = req.body


  const alipaySdk = new AlipaySdk({
    // 设置应用 ID
    appId: '9021000150603290',
    // 设置应用私钥
    privateKey: "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCqMyujNEG34BEFfrFcMMEr9VAXLnQzxBmQeBL1CQkz1x1Vz3UJDBWq3yh4mfMBz3/9xEfOcajSAVtyIG9rwfkyVcTAtEN2I6raCiAww/XWWFBQANh8iM3F3ymcflcHpsbvJBrgKiQPpnC1xbDkMO2Q6XYNRxLtT1tI2kSzLg5z9X1LggAoT0WKoLRU/eg8dI7s4PXV9gMue4KiZoNKMIkbMXiL0HUPiO5vO6rVrjqL85Q58mB481Iv9cOIy/T55u0FAjBleIvkLBb6QtGCQONUOPNXRScP/XdcEFlUAzWBmSjilNW/nxrMoX+nWcYgnhS4XlQyQXEgqyw9T+xCz8RnAgMBAAECggEAfFY3id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wjrqm3Y8eLwiNsv+IZPzRPkPS83w2zVt8qbPbSVbW1OFWzvnChBqvMRH6T0nhuV/Y5P19zPBdocozpKjbf6aU8FoRah66Z5VuKWjLBjissBB38rzfay7jJTa8lm90yBHl2P9jj",
    // 设置支付宝公钥
    alipayPublicKey: "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhBe1DJp1oMojyRLBv53i461lf46SrUFRS/xSroN6y7eXYyXhm/+Wd+9tNvpB67VzYLULkjCWQDy7y8D/SvrG5hm0LgRtX2rrRkvbbHAHKv4ebfi+PvxKlo/4TLkGwtyQGy6PAPoXwt/UTFr6x2oyhlh8x3M1AT3ANbGByCwATkvoTdMtxeGMMeBM/RUfuT/HdZBCgvc9fIyKDE07zgnG7jb0EXF4wSJ7oQQxQ/7qY2uhmbNmOSWohqhsv//wtud62oEZoZz2XaQnk/kZ5Q11lzksaTqVo8JtVFP0ERr3yhiFLWDSdrqFi4JldutI7EL4ztSmsWi98JDAUOrofd7SeQIDAQAB",
    // 密钥类型，请与生成的密钥格式保持一致，参考平台配置一节
    // keyType: 'PKCS1',
    // 设置网关地址，默认是 https://openapi.alipay.com
    // endpoint: 'https://openapi.alipay.com',
    "gateway": "https://openapi-sandbox.dl.alipaydev.com/gateway.do"
  })

  //   支付商品信息
  const formData = new AlipaySdkFormData();
  formData.addField("bizContent", {
    // 一个订单只能支付一次
    out_trade_no: outTradeNo,
    product_code: "FAST_INSTANT_TRADE_PAY",  // 支付信息的订单编号 前端在确定订单的时候会生产订单信息 包括订单编号
    subject: subject, // 商品名称
    body: "会员开通",
    total_amount: totalAmount  // 支付金额
  })

  // 第三方接口 实现支付功能


  // 支付成功后跳转到前端的一个路由
  formData.addField("returnUrl", "http://localhost:5173/vippage")

  // 支付有PC端和移动端 
  //   alipay.trade.page.pay PC端
  // alipay.trade.wap.pay 移动端
  let result = await alipaySdk.exec("alipay.trade.wap.pay", {}, {
    formData: formData
  })
  console.log(result, 123123);
  res.send(result)

})

module.exports = router;